package com.ruoyi.project.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.oss.AliyunOssClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysNotice;
import com.ruoyi.project.system.service.ISysNoticeService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 公告 信息操作处理
 *
 * @author ruoyi
 */
@Api(value = "公告管理")
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {
    @Resource
    private ISysNoticeService noticeService;

    @Resource
    private AliyunOssClient aliyunOssClient;

    @Value("${oss.url}")
    private String aliyunUrl;


    /**
     * 获取通知公告列表
     */
    @ApiOperation("获取列表")
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotice notice) {
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }

    /**
     * 根据通知公告编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId) {
        return AjaxResult.success(noticeService.selectNoticeById(noticeId));
    }

    /**
     * 新增通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice) {
        notice.setCreateBy(getUsername());
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice) {
        notice.setUpdateBy(getUsername());
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds) {
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }

    @ApiOperation("下载附件")
    @GetMapping(value = "/download/{noticeId}")
    public AjaxResult download(@PathVariable Long noticeId) throws Exception {
        SysNotice sysNotice = noticeService.selectNoticeById(noticeId);
        String url = sysNotice.getFileUrl();
        if (StringUtils.isEmpty(url)) {
            return AjaxResult.error("附件不存在!");
        }
        return AjaxResult.success("下载成功!", url);
    }


    @ApiOperation("上传附件")
    @PostMapping(value = "/billUpload")
    @ResponseBody
    public AjaxResult billUpload(@RequestParam("file") MultipartFile file, @RequestParam("id") Long id) throws Exception {
        String fileDate = DateUtil.format(new Date(), "yyyyMMdd");
        String fileName = file.getOriginalFilename();
        SysNotice sysNotice = noticeService.selectNoticeById(id);
        if (sysNotice == null) {
            System.out.println("公告不存在!");
        }
        String path = "match" + "/" + fileDate + "/" + fileName;
        String url = aliyunUrl + "/" + path;
        sysNotice.setFileFlag("是");
        sysNotice.setFileUrl(url);
        try {
            InputStream inputStream = file.getInputStream();
            aliyunOssClient.uplodafile(path, inputStream);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("附件上传失败!");
        }
        noticeService.updateNotice(sysNotice);
        return AjaxResult.success("附件上传成功!");
    }


}
